package com.zzyl.nursing.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.framework.config.CodeGenerator;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.nursing.vo.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.vo.CheckInElderVo;
import com.zzyl.nursing.vo.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

/**
 * 入住Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-18
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键chuagjchaungjinchaungjianyigechuangjianyigeshaichuangjianyigechuangchuchuangjanyigechuagjajyi
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInApplyDto) {
        //合同表
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();
        //老人表
        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        //入住配置
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        //家人表
        List<ElderFamilyDto> elderFamilyDtoList = checkInApplyDto.getElderFamilyDtoList();

        //1.判断老人是否已经入住,查身份证
        LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper<>();
        elderQueryWrapper.eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo());
        elderQueryWrapper.eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(elderQueryWrapper);
        if (ObjectUtils.isNotEmpty(elder)) {
            throw new BaseException("老人已入住");
        }

        //2.更新床位的状态,已入住
        Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //3.新增或修改老人数据
        elder = insertUpdate(checkInElderDto, bed);

        //4.新增合同
        String contractNo = "HT" + CodeGenerator.generateContractNumber();
        extracted(checkInContractDto, elder, contractNo, checkInConfigDto);
        //5.新增入住记录
        Long checkInId = insertchenkin(checkInApplyDto, elder, elderFamilyDtoList);

        //新增入住配置
        insertConfig(checkInApplyDto, checkInId);

    }

    private Long insertchenkin(CheckInApplyDto checkInApplyDto, Elder elder, List<ElderFamilyDto> elderFamilyDtoList) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(elderFamilyDtoList));
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn.getId();
    }


    private void insertConfig(CheckInApplyDto checkInApplyDto, Long checkInId) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkInId);
        checkInConfigMapper.insert(checkInConfig);
    }


    //新增合同
    private void extracted(CheckInContractDto checkInContractDto, Elder elder, String contractNo, CheckInConfigDto checkInConfigDto) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInContractDto, contract);
        contract.setElderName(elder.getName());
        contract.setElderId(elder.getId());
        contract.setContractNumber(contractNo);
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        contract.setStatus(1);
        contractMapper.insert(contract);
    }

    private Elder insertUpdate(CheckInElderDto checkInElderDto, Bed bed) {
        Elder elder1 = new Elder();

        BeanUtils.copyProperties(checkInElderDto, elder1);

        elder1.setBedNumber(bed.getBedNumber());
        elder1.setBedId(bed.getId());
        elder1.setStatus(1);


        LambdaQueryWrapper<Elder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo()).ne(Elder::getStatus, 1);
        Elder elderDb = elderMapper.selectOne(lambdaQueryWrapper);
        if (ObjectUtils.isNotEmpty(elderDb)) {
            elderMapper.updateById(elder1);
        } else {
            elderMapper.insert(elder1);
        }
        return elder1;
    }





        //计算年龄的方法
        public  int calculateAge(String idCard) {
            // 提取身份证中的出生日期部分
            String birthDateStr = idCard.substring(6, 14);
            // 定义日期格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            // 将字符串转换为LocalDate对象
            LocalDate birthDate = LocalDate.parse(birthDateStr, formatter);
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            // 计算年龄
            return Period.between(birthDate, currentDate).getYears();
        }





    @Transactional
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo vo = new CheckInDetailVo();

        //1.入住配置信息
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        CheckIn checkIn = checkInMapper.selectById(id);
        BeanUtils.copyProperties(checkIn, checkInConfigVo);

        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>().eq(CheckInConfig::getCheckInId, id));
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);

        vo.setCheckInConfigVo(checkInConfigVo);


        //老人响应信息
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        BeanUtils.copyProperties(elder, checkInElderVo);

        //年龄
        int i = calculateAge(elder.getIdCardNo());
        checkInElderVo.setAge(i);

        vo.setCheckInElderVo(checkInElderVo);


        //家属信息
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(remark, ElderFamilyVo.class);
        vo.setElderFamilyVoList(elderFamilyVoList);

            //合同信息
        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getElderId, checkIn.getElderId()));
        vo.setContract(contract);

        return vo;
    }


}
